<?php

namespace app\company\controller;

use app\company\validate\WarehouseStorageValidate;
use app\service\traits\Crud;
use app\company\model\WarehouseStorage as WarehouseStorageModel;
use app\service\traits\Storage;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Request;
use think\Response;
use app\company\model\Warehouse;

class WarehouseStorage extends Base
{
    private WarehouseStorageModel $model;

    use Crud;
    use Storage;

    public function initialize()
    {
        parent::initialize();
        $this->model         = new WarehouseStorageModel();
        $this->validateClass = WarehouseStorageValidate::class;
        $this->withSearch    = 'id,line,layer,row,name,warehouse_id,warehouse_area_id';
        $this->field         = 'id,name,warehouse_id,warehouse_area_id';
    }

    /**
     * @return Response
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function list(): Response
    {
        $param = request()->param();
        validate($this->validateClass)
            ->scene('list')
            ->check($param);
        $sql = $this->model;
        if ($this->with) $sql = $sql->with(explode(",", $this->with));
        $sql = $sql->withSearch($this->withSearch, $param);
        //添加公司限制 --得到公司仓库ID
        $warehouse_ids = Warehouse::gs()
                                  ->column('id');
        $sql           = $sql->where('warehouse_id', 'in', $warehouse_ids);
        if (request()->param('names', '')) {
            $sql = $sql->whereIn('name', $param['names']);
        }
        $sql   = $sql->field($this->field);
        $count = $sql->count();
        if (Request::param('is_export', 0) != 1) $sql = $sql->page($param['page'], $param['limit']);
        $list = $sql->order('id asc')
                    ->select();
        $list = $this->format($list);
        return $this->success('获取成功', compact('count', 'list'));
    }

    public function format($list): mixed
    {
        return $list->each(function ($item) {
            $item->warehouse_name      = $item->warehouse()
                                              ->value('name');  //库名
            $item->warehouse_area_name = $item->warehouseArea()
                                              ->value('name');  //库区名
            $item->quantity            = $item->companyOrderStorages()
                                              ->sum('quantity');//库位商品数量
            $item->goods_type          = $item->companyOrderStorages()
                                              ->group("goods_rule_id")
                                              ->count();        //库位商品种类
        });
    }


    public function add(): Response
    {
        $param = request()->param();
        validate($this->validateClass)
            ->scene('add')
            ->check($param);
        $this->model->startTrans();
        try {
            //获取当前最后一个line值
            $lineName = $this->model
                ->where(['warehouse_area_id' => $param['warehouse_area_id']])
                ->order('line', 'desc')
                ->value('line');

            // 行
            $lines = $param['line'];
            // 列
            $rows = $param['row'];
            // 层
            $layers = $param['layer'];
            // 组
            $groups = $param['group'];

            $arr   = [];
            $array = [];
            // 根据行、组、层生成码
            for ($line = 1; $line <= $lines; $line++) {
                $lineName = $lineName ? $this->getNextVariable($lineName) : "A";
                for ($group = 1; $group <= $groups; $group++) {
                    $groupName  = getPaddedNumber($group, 2);
                    for ($row = 1; $row <= $rows; $row++) {
                        $rowName = getPaddedNumber($row, 2);
                        for ($layer = 1; $layer <= $layers; $layer++) {
                            $layerName                = getPaddedNumber($layer, 2);
                            $arr['layer']             = $layerName;
                            $arr['line']              = $lineName;
                            $arr['row']               = $rowName;
                            $arr['group']             = $groupName;
                            $arr['name']              =
                                $lineName . "-" . $groupName . "-" . $rowName . "-" . $layerName;
                            $arr['warehouse_id']      = $param['warehouse_id'];
                            $arr['warehouse_area_id'] = $param['warehouse_area_id'];
                            $array[]                  = $arr;
                        }
                    }
                }
            }
            $this->model->saveAll($array);
        } catch (\Exception $e) {
            $this->model->rollback();
            return $this->error('创建失败');
        }
        $this->model->commit();
        return $this->success('创建成功');
    }


}